/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.hva.web.mvcwebapp.doa;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import nl.hva.web.mvcwebapp.models.Assignment;
import nl.hva.web.mvcwebapp.models.Test;
import nl.hva.web.mvcwebapp.models.Chapter;
import nl.hva.web.mvcwebapp.models.User;
import nl.hva.web.mvcwebapp.models.Course;
import nl.hva.web.mvcwebapp.models.MadeAssignment;
import nl.hva.web.mvcwebapp.models.UploadAssignment;
import nl.hva.web.mvcwebapp.models.UploadedAssignments;
import nl.hva.web.mvcwebapp.models.UserTest;
import nl.hva.web.mvcwebapp.models.UserTestPK;
import nl.hva.web.mvcwebapp.models.Widget;
import nl.hva.web.mvcwebapp.service.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.transform.Transformers;

/**
 *
 * @author Thijs
 */
public class UploadAssignmentDAO {

    public UploadAssignmentDAO() {
    }

    public static List<UploadedAssignments> getAllUploadAssignments(int chapter_id) {

        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Test.class);
        SessionFactory factory = config.configure().buildSessionFactory();
        Session session = factory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        Query queryResult = session.createQuery("FROM UploadedAssignments WHERE chapter_chapterid='" + chapter_id + "'"
                                                + "ORDER BY user_id");

        List<UploadedAssignments> uploadassignment_list = queryResult.list();
//        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//        Transaction tx = session.beginTransaction();
//        List<Chapter> chapter_list = session.createCriteria(Chapter.class).list();
//        tx.commit();
        tx.commit();
        return uploadassignment_list;
    }
    public static List<UploadAssignment> getAllAssignments(int chapter_id) {

        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Test.class);
        SessionFactory factory = config.configure().buildSessionFactory();
        Session session = factory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        Query queryResult = session.createQuery("FROM UploadAssignment WHERE chapter_chapterid='" + chapter_id + "'");

        List<UploadAssignment> uploadassignment_list = queryResult.list();
//        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//        Transaction tx = session.beginTransaction();
//        List<Chapter> chapter_list = session.createCriteria(Chapter.class).list();
//        tx.commit();
        tx.commit();
        return uploadassignment_list;
    }

    public static List<UploadedAssignments> getAllDocumentsForUser(int chapter_id, int user_id) {
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Test.class);
        SessionFactory factory = config.configure().buildSessionFactory();
        Session session = factory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        Query queryResult = session.createQuery("FROM UploadedAssignments WHERE chapter_chapterid='" + chapter_id + "' AND user_id = '" + user_id + "'");

        List<UploadedAssignments> uploadassignment_list = queryResult.list();
        tx.commit();
        return uploadassignment_list;
    }
    public static List<UploadedAssignments> getAllDocuments(int chapter_id) {
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Test.class);
        SessionFactory factory = config.configure().buildSessionFactory();
        Session session = factory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        Query queryResult = session.createQuery("FROM UploadedAssignments WHERE chapter_chapterid='" + chapter_id + "'");

        List<UploadedAssignments> uploadassignment_list = queryResult.list();
        tx.commit();
        return uploadassignment_list;
    }
    /*public static List<UserTest> getUserTest(int test_id) {
     AnnotationConfiguration config = new AnnotationConfiguration();
     config.addAnnotatedClass(Test.class);
     SessionFactory factory = config.configure().buildSessionFactory();
     Session session = factory.getCurrentSession();
     session.beginTransaction();
     Query queryResult = session.createQuery("FROM UserTest WHERE TEST_ID='"+test_id+"' AND USER_ID='"+1+"'");
     List<UserTest> test_list = queryResult.list();
     return test_list;
     }
     public static List<UserTest> getAllUserTest(int user_id) {
     AnnotationConfiguration config = new AnnotationConfiguration();
     config.addAnnotatedClass(Test.class);
     SessionFactory factory = config.configure().buildSessionFactory();
     Session session = factory.getCurrentSession();
     session.beginTransaction();
     Query queryResult = session.createQuery("FROM UserTest WHERE USER_ID='"+user_id+"'");
     List<UserTest> test_list = queryResult.list();
     return test_list;
     }*/

    public static UploadedAssignments approveAssignment(int document_id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        UploadedAssignments document = (UploadedAssignments) session.load(UploadedAssignments.class, document_id);
        document.setApproved(1);
        session.save(document);
        tx.commit();

        //Course course = new Course(1, 1, "Java", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendiere ante, id porttitor ipsum semper non. Etiam mollis euismod dapibus. Phasellus vel turpis sem. Vestibulum dui ...", "1", "http://www.downloadstad.nl/screenshot/Java.jpg");
        return document;
    }

    public static UploadAssignment getUploadAssignment(int uploadassignment_id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        UploadAssignment uploadassignment = (UploadAssignment) session.get(UploadAssignment.class, uploadassignment_id);
        tx.commit();

        //Course course = new Course(1, 1, "Java", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendiere ante, id porttitor ipsum semper non. Etiam mollis euismod dapibus. Phasellus vel turpis sem. Vestibulum dui ...", "1", "http://www.downloadstad.nl/screenshot/Java.jpg");
        return uploadassignment;
    }

    public static UploadedAssignments getDocument(int document_id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        UploadedAssignments document = (UploadedAssignments) session.get(UploadedAssignments.class, document_id);
        tx.commit();

        //Course course = new Course(1, 1, "Java", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendiere ante, id porttitor ipsum semper non. Etiam mollis euismod dapibus. Phasellus vel turpis sem. Vestibulum dui ...", "1", "http://www.downloadstad.nl/screenshot/Java.jpg");
        return document;
    }

    public static ArrayList insertTestForUser(HttpServletRequest request, Test test) {
        ArrayList validation_errors = new ArrayList();
        //int userid = Integer.valueOf("" + session_user.getAttribute("user_id"));
        HttpSession session_user = request.getSession(true);
        String firstname = (String) session_user.getAttribute("user_firstname");
        int user_id = 0;
        if (firstname != null) {
            user_id = Integer.valueOf("" + session_user.getAttribute("user_id"));
        }
        User user = UserDAO.getUser(user_id);
        UserTest testuser = new UserTest();
        UserTestPK pk = new UserTestPK();
        pk.setTest(test);
        pk.setUser(user);
        testuser.setPk(pk);

        ArrayList saved_answerlist = new ArrayList();

        String[] assignments = request.getParameterValues("assignment");
        boolean error = false;
        double max_score = 0;
        double score_gained = 0;
        double end_score = 0;
        for (int i = 0; i < assignments.length; i++) {
            int assignmentid = Integer.parseInt(request.getParameter("assignment_" + assignments[i]));
            Assignment assignment = AssignmentDAO.getAssignment(assignmentid);
            MadeAssignment madeassignment = new MadeAssignment();


            if (request.getParameter("answer_" + (i + 1)) != null && !request.getParameter("answer_" + (i + 1)).isEmpty()) {
                String[] answers = request.getParameterValues("answer_" + (i + 1));
                int score = 0;
                for (int j = 0; j < answers.length; j++) {
                    saved_answerlist.add(answers[j]);
                    if (assignment.getAssignmenttype() == 0) {
                        //check box
                        if (AssignmentDAO.getAnswer(Integer.parseInt(answers[j])).getAnswerright() == 1) {
                            score = score + 1;
                        } else {
                            score = score - 1;
                        }

                    } else {
                        //radio box
                        if (AssignmentDAO.getAnswer(Integer.parseInt(answers[j])).getAnswerright() == 1) {
                            score = score + 2;
                        }
                    }
                    System.out.println("Submit - Answer: " + answers[j] + " Assignment: " + assignments[i]);
                }
                if (score < 0) {
                    madeassignment.setRight(0);
                    madeassignment.setScore(0);
                    score = 0;
                } else if (score == 1) {
                    madeassignment.setRight(1);
                    madeassignment.setScore(1);
                } else if (score >= 2) {
                    madeassignment.setRight(2);
                    madeassignment.setScore(2);
                    score = 2;
                }

                //madeassignment.setAssignment(assignment);
                //madeassignment.setUsertest(testuser);
                //testuser.addMadeassignments(madeassignment);
                score_gained = score_gained + score;
                max_score = max_score + 2;
            } else {
                error = true;
                //Not all answers are filled in.
            }
        }


        if (!error) {
            System.out.println("MAX SCORE = " + max_score);
            System.out.println("SCORE GAINED = " + score_gained);
            end_score = (score_gained) / (max_score) * 100;
            int completed = 0;
            if (end_score > 55) {
                completed = 1;
            }
            System.out.println("COMPLETED = " + completed + " with SCORE = " + (int) end_score);

            //testuser.setChapter(test.getChapter());
            testuser.setCompleted(completed);
            testuser.setScore((int) end_score);
            try {
                Session session = HibernateUtil.getSessionFactory().getCurrentSession();
                Transaction tx = session.beginTransaction();
                session.save(testuser);
                tx.commit();
            } catch (Exception e) {

                e.printStackTrace();
            }
            return null;
        } else {
            return saved_answerlist;
        }
    }
    // Uploaded Assignment

    public static ArrayList insertDocument(HttpServletRequest request, UploadAssignment uploadassignment, User user) {
        ArrayList validation_errors = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        UploadedAssignments assignment = getDocumentFromRequest(request, uploadassignment, null, user);
        session.save(assignment);
        tx.commit();
        return validation_errors;
    }

    public static ArrayList updateDocument(HttpServletRequest request, UploadedAssignments assignment, User user) {
        ArrayList validation_errors = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        UploadedAssignments updatedassignment = getDocumentFromRequest(request, null, assignment, user);
        session.update(updatedassignment);
        tx.commit();
        return validation_errors;
    }

    // Upload Assignment
    public static ArrayList insertUploadAssignment(HttpServletRequest request, Chapter chapter) {
        ArrayList validation_errors = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        UploadAssignment assignment = getUploadAssignmentFromRequest(request, chapter, null);
        session.save(assignment);
        tx.commit();
        return validation_errors;
    }

    public static ArrayList updateUploadAssignment(HttpServletRequest request, UploadAssignment assignment) {
        ArrayList validation_errors = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        UploadAssignment updatedassignment = getUploadAssignmentFromRequest(request, null, assignment);
        session.update(updatedassignment);
        tx.commit();
        return validation_errors;
    }

    public static void deleteTest(int uploadassignment_id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        UploadAssignment tempassignment = (UploadAssignment) session.load(UploadAssignment.class, uploadassignment_id);
        session.delete(tempassignment);
        tx.commit();
    }

    private static UploadedAssignments getDocumentFromRequest(HttpServletRequest request, UploadAssignment assignment, UploadedAssignments uploaded_assignment, User user) {
        if (uploaded_assignment == null) {
            uploaded_assignment = new UploadedAssignments();
        }

        if (request.getParameter("documentid") != null && !request.getParameter("documentid").isEmpty()) {
            uploaded_assignment.setUploadedassignmentid(Integer.parseInt(request.getParameter("documentid")));
        }
        if (request.getParameter("description") != null && !request.getParameter("description").isEmpty()) {
            uploaded_assignment.setUploadedassignmentdescription(request.getParameter("description"));
        }
        if (request.getAttribute("path_in_server") != null) {
            uploaded_assignment.setDocumentpath((String) request.getAttribute("path_in_server").toString());
        }
        if (assignment != null) {
            uploaded_assignment.setChapter(assignment.getChapter());
            uploaded_assignment.setUploadassignment(assignment);
        }
        if (user != null) {
            uploaded_assignment.setUser(user);
        }
        return uploaded_assignment;
    }

    private static UploadAssignment getUploadAssignmentFromRequest(HttpServletRequest request, Chapter chapter, UploadAssignment assignment) {
        if (assignment == null) {
            assignment = new UploadAssignment();
        }

        if (request.getParameter("assignmentid") != null && !request.getParameter("assignmentid").isEmpty()) {
            assignment.setUploadassignmentid(Integer.parseInt(request.getParameter("assignmentid")));
        }
        if (request.getParameter("assignmentname") != null && !request.getParameter("assignmentname").isEmpty()) {
            assignment.setUploadassignmentname(request.getParameter("assignmentname"));
        }
        if (request.getParameter("assignmentdescription") != null && !request.getParameter("assignmentdescription").isEmpty()) {
            assignment.setUploadassignmentdescription(request.getParameter("assignmentdescription"));
        }
        if (chapter != null) {
            assignment.setChapter(chapter);
        }
        return assignment;
    }
}
